package com.shungen.apicloud.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shungen.apicloud.annotation.AuthCheck;
import com.shungen.apicloud.common.BaseResponse;
import com.shungen.apicloud.common.ErrorCode;
import com.shungen.apicloud.common.PageRequest;
import com.shungen.apicloud.common.ResultUtils;
import com.shungen.apicloud.constant.UserConstant;
import com.shungen.apicloud.exception.ThrowUtils;
import com.shungen.apicloud.model.dto.point.PointChangeRequest;
import com.shungen.apicloud.model.entity.PointTransaction;
import com.shungen.apicloud.model.entity.User;
import com.shungen.apicloud.model.vo.LoginUserPointBalanceVO;
import com.shungen.apicloud.model.vo.PointTransactionVO;
import com.shungen.apicloud.service.PointTransactionService;
import com.shungen.apicloud.service.UserService;
import com.shungen.apicloud.utils.JWTUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shungen
 * @date 2024年08月08日 16:05
 */

@RestController
@RequestMapping("/point")
public class PointController {

    @Resource
    private UserService userService;

    @Resource
    private PointTransactionService pointTransactionService;


    /**
     * 管理员给用户添加积分
     * - 1.新增积分变动记录
     * - 2.更新用户余额
     * @param pointChangeRequest
     * @return
     */
    @PostMapping("/changePoint")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public BaseResponse<Long> addPointForUser(@RequestBody PointChangeRequest pointChangeRequest){
        ThrowUtils.throwIf(pointChangeRequest == null, ErrorCode.PARAMS_ERROR,"缺少请求参数");
        PointTransaction pointTransaction = new PointTransaction();
        BeanUtils.copyProperties(pointChangeRequest,pointTransaction);
//        System.out.println(pointTransaction);
        boolean addResult = pointTransactionService.save(pointTransaction);
        ThrowUtils.throwIf(!addResult,ErrorCode.OPERATION_ERROR,"新增积分变动记录失败");
        boolean updateBalanceResult = userService.updatePointBalance(pointChangeRequest.getUserId(), pointChangeRequest.getChangeAmount());
        ThrowUtils.throwIf(!updateBalanceResult,ErrorCode.OPERATION_ERROR,"更新用户余额失败");
        return ResultUtils.success(pointTransaction.getId());//返回变动记录id
    }


    /**
     * 查询自己的积分余额
     * @return
     */
    @GetMapping("/get/my")
    @AuthCheck
    public BaseResponse<LoginUserPointBalanceVO> getLoginUserPointBalance(HttpServletRequest request){
        //拿到用户id
        String token = request.getHeader("token");
        Long userId = Long.valueOf(JWTUtil.getClaimFromToken(token, "id"));
        User loginUser = userService.getById(userId);
        ThrowUtils.throwIf(loginUser == null,ErrorCode.OPERATION_ERROR,"用户不存在");
        LoginUserPointBalanceVO loginUserPointBalanceVO = new LoginUserPointBalanceVO();
        loginUserPointBalanceVO.setUserAccount(loginUser.getUserAccount());
        loginUserPointBalanceVO.setPointBalance(loginUser.getPointBalance());
        return ResultUtils.success(loginUserPointBalanceVO);
    }

    @AuthCheck
    @PostMapping("/pointtransaction/page/my")
    public BaseResponse<Page<PointTransactionVO>> getLoginUserPointTransactionPageData(@RequestBody PageRequest pageRequest, HttpServletRequest request){
        //拿到用户id
        String token = request.getHeader("token");
        Long userId = Long.valueOf(JWTUtil.getClaimFromToken(token, "id"));
        Page<PointTransaction> pointTransactionPage = pointTransactionService.getPageDataByUserId(userId, pageRequest.getCurrent(), pageRequest.getPageSize());
        Page<PointTransactionVO> pointTransactionVOPage = new Page<>();
        BeanUtils.copyProperties(pointTransactionPage,pointTransactionVOPage);
        List<PointTransaction> pointTransactionList = pointTransactionPage.getRecords();
        List<PointTransactionVO> pointTransactionVOList = pointTransactionList.stream().map(x -> {
            PointTransactionVO pointTransactionVOInner = new PointTransactionVO();
            BeanUtils.copyProperties(x, pointTransactionVOInner);
            return pointTransactionVOInner;
        }).collect(Collectors.toList());
        pointTransactionVOPage.setRecords(pointTransactionVOList);
        return ResultUtils.success(pointTransactionVOPage);
    }





}
